/**
 * Program  : MainActivity.java
 * Author   : long
 * Create   : 2015年12月28日 上午10:10:11
 *
 * Copyright 2015 by Embedded Internet Solutions Inc.,
 * All rights reserved.
 *
 * This software is the confidential and proprietary information
 * of Embedded Internet Solutions Inc.("Confidential Information").  
 * You shall not disclose such Confidential Information and shall 
 * use it only in accordance with the terms of the license agreement 
 * you entered into with Embedded Internet Solutions Inc.
 *
 */
	
package cn.broadin.app.hotel;

import java.io.File;
import java.io.IOException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import cn.broadin.app.hotel.app.AppConfig;
import cn.broadin.app.hotel.app.AppContext;
import cn.broadin.app.hotel.config.WiFiAPService;
import cn.broadin.app.hotel.config.WifiHotUtil;
import cn.broadin.app.hotel.service.ListenNetStateService;
import cn.broadin.app.hotel.service.ListenNewVersionService;
import cn.broadin.app.hotel.startWebapp.StartWebView;
import cn.broadin.app.hotel.task.AdvDownloadTask;
import cn.broadin.app.hotel.util.MacAddressHelper;
import cn.broadin.app.hotel.util.TvAnimator;
import cn.broadin.app.hotel.util.UtilFile;
import cn.broadin.app.hotel.util.XHttpProxy;
import cn.broadin.app.hotel.util.XLog;
import cn.broadin.app.hotel.util.XToast;
import cn.broadin.app.hotel.util.XUIHelper;
import cn.broadin.app.hotel.util.XUtils;
import pl.droidsonroids.gif.GifImageView;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;

/**
 * 株洲UI-主页面
 * 
 * @author   long
 * @version  1.0.0
 * @date 2015年12月28日上午10:10:11
 */
/**
 * @author MR-Deng
 *
 */
@SuppressLint("NewApi")
public class MainActivity extends BaseActivity implements View.OnFocusChangeListener, View.OnClickListener, SurfaceHolder.Callback{
	
	private ImageView focusView;
	
	private TextView showDaTextView;
	
	private FrameLayout liveWindow;				// 视频直播窗口
	private ImageView liveImageView;
	private ImageView liveWindowLoading;		// loading状态
	private Animation rotateAnimation;
	
	private ImageView videoImageView;
	private ImageView musicImageView;
	private GifImageView advImageView;
	private ImageView photoImageView;
	private ImageView fireImageView;
	private ImageView aboutImageView;
	
	private LinearLayout marqueeLinearLayout;
	private TextView marqueeTextView;
	
	private boolean networkFlag = false;			// 网络连接标志
	
	public static final String NET_CHANGED_ACTION = "com.pd.NET_CHANGED_ACTION";
	public static final String FIRE_HAPPEN_ACTION = "com.pd.FIRE_HAPPEN_ACTION"; 
	public static final String FIRE_OVER_ACTION = "com.pd.FIRE_OVER_ACTION";
	
	private boolean refreshDateFlag = false;
	

	private boolean deviceAuthFlag = false;				// 设备授权标志
	private RoomInitStatus roomInfoInitFlag = RoomInitStatus.UNDO;			// 房间数据是否已经初始化
	
	
	// 视频播放对象
	private MediaPlayer mMediaPlayer;
	private SurfaceView mSurfaceView;
	private SurfaceHolder mSurfaceHolder;
	// 播放界面宽度
	private int mVideoWidth;
	// 播放界面高度
	private int mVideoHeight;
	
	public static String liveUrl = null;
	public static String indexVideoFile = null;
	
	private NetworkStatusReceiver networkReceiver;
	
	private String introUrl;
	public static String marqueeText = "暂无提示信息";

	public static String startVideoUrl;

	public static String hotelsIntroUrl;  //Web 应用入口
	public static String ProjectName;   //Web项目名称
	public  String macNum = "";
    public static final String NTP_SERVER = "ntp_server"; 
    private String Hotname = "";
    private String Hotpassword = "";
    private String auto_openFlag = "";
    private String HotStatus = "";
    boolean getConfigFlag = false;
    private WifiHotUtil wifiHotUtil;    
    private String oldMarqueeText = "";
    public String productInfo = null;
    public String chipsInfo = null;
	private String authResult = "true";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.d("dyh---:","MainActivity.onCreate");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main_new);
		
		AppContext appContext = (AppContext)getApplicationContext();  //获取全局变量app
		productInfo = appContext.getProductInfo();
		chipsInfo = appContext.getChipsInfo();
		if(productInfo == null || productInfo.equals("")) {  //再获取一次厂家信息
			productInfo = XUtils.getSystemInfo();
		}
		if(chipsInfo == null || chipsInfo.equals("")) {  //再获取一次厂家信息
			chipsInfo = XUtils.getChipsInfo();
		}
		
		
		authResult = appContext.getAuthFlag();	
		if(authResult == null || authResult.equals("")) {
			authResult = "true";
		}
		
		WiFiAPService.startService(this);
		wifiHotUtil = new WifiHotUtil(this);
		
		//初始化相关参数
		macNum = MacAddressHelper.getInstance().getMacAddress(this);
		

		getIndexVideoPath();
		
		// 界面初始化
		initView();
		
		
		//设置热点
		if ( Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
			String HotSpotconfigDir = "/data/local/Hotconfig/";
			String HotSpotconfigFile = "Hotspot.txt";	
			File HotSpotfile = new File(HotSpotconfigDir,HotSpotconfigFile);		
			if(HotSpotfile.exists() && HotSpotfile.length() != 0) {
				getHotspotConfig(HotSpotconfigDir,HotSpotconfigFile);
			}			
		}
		
		// 注册广播
		registerBroadcastReceiver();
		
		// 启动网络监听服务
		Intent networkIntent = new Intent(this, ListenNetStateService.class); 
		startService(networkIntent);
		
		
		/*Intent mService = new Intent(MainActivity.this, ListenNewVersionService.class); 
		Bundle stbstatebundle = new Bundle();  
		String stbStateUrl = stbStateUrlFormat(MainActivity.this);
		stbstatebundle.putString("stbStateUrl", stbStateUrl);
		stbstatebundle.putString("fireStateUrl", AppConfig.fireStateUrl);
		mService.putExtras(stbstatebundle);
		startService(mService);
		*/
		
		if(getConfigFlag) {
			XLog.d("dyh : stb HotspotConfig-start");
			HotspotConfig.start();
		}
	}
	
	
	/**
	 * 
	 */
	String saveDirPath = "";
	private void getIndexVideoPath() {
		// TODO 自动生成的方法存
		XLog.d("indexVideoFile111=productInfo: " + productInfo);
		if(productInfo == null || productInfo.equals("")) {  //再获取一次厂家信息
			productInfo = XUtils.getSystemInfo();
		}
		
		XLog.d("indexVideoFile222=productInfo: " + productInfo);
		if(productInfo.equals("MBX")) {  //智诺达S805方案
			saveDirPath = "/mnt/sdcard";
		} else if(productInfo.equals("CNCR") || productInfo.equals("JIUZHOU") || productInfo.equals("Skyworth")) { //九州和初灵方案
			saveDirPath = "/data/local";
		}
		else {  //默认方案
			saveDirPath = "/data/local";
		}
		
		XLog.d("indexVideoFile333=saveDirPath: " + saveDirPath);
		String tempFilePath = saveDirPath + "/indexVideo";
		String tempFileName = "indexVideo.mp4";
		File file = new File(tempFilePath,tempFileName);
		if(!file.exists() || file.length() == 0) {
			indexVideoFile = liveUrl;
		} else {
			indexVideoFile = saveDirPath + "/indexVideo/indexVideo.mp4";
		}
		
		XLog.d("indexVideoFile444====: " + indexVideoFile);
	}

	public static String stbStateUrlFormat(Context mContext){
		String macNum = MacAddressHelper.getInstance().getMacAddress(mContext);
		String tempCode = AppConfig.secuCode + macNum + AppConfig.versionCode;
		String signCode = XUtils.md5(tempCode);
		XLog.d("tempCode: " + tempCode + ", signCode: " + signCode);
		
		String pingTempCode = AppConfig.secuCode + macNum;
		String pingsignCode = XUtils.md5(pingTempCode);
		String stbStateUrl = AppConfig.stbStateUrl + macNum + "&sign=" + pingsignCode;
		return stbStateUrl;
	}
	
	private void getHotspotConfig(String dirName, String FileName) {
		String fileContent = "";
		fileContent = UtilFile.readFile(dirName,FileName);
		if (fileContent.equals("")) {
			Log.d("dyh---:","getHotspotConfig---> no config");
		} else {
			String[] result = fileContent.split(";");
			Hotname = result[0];
			Hotpassword = result[1];
			auto_openFlag = result[2];	
			getConfigFlag = true;
		}
	}
	
	Thread HotspotConfig = new Thread(new Runnable(){

		@Override
		public void run() {
			// TODO 自动生成的方法存根
			System.out.println("dyh-----auto_openFlag--auto_openFlag = "+auto_openFlag);
			if(auto_openFlag.equals("true")) {
				int tempType = 1; //需要密码
				if(Hotpassword.equals("")) {
					tempType = 0; //不需要密码
				}
				
				HotStatus = "on";
				wifiHotUtil.startWifiAp(Hotname,Hotpassword,tempType);
			} else {
				HotStatus = "off";
				wifiHotUtil.closeWifiAp();
			}
		}
		
	});
	
	private String hiddenKey = "";
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if(event.getAction() == KeyEvent.ACTION_DOWN){
			// 焦点位于活力星沙  按123进入参数配置页面
			if(aboutImageView.hasFocus()){
				if(event.getKeyCode() == KeyEvent.KEYCODE_1){
					hiddenKey = hiddenKey + "1";
				} else if(event.getKeyCode() == KeyEvent.KEYCODE_2){
					hiddenKey = hiddenKey + "2";
				} else if(event.getKeyCode() == KeyEvent.KEYCODE_3){
					hiddenKey = hiddenKey + "3";
				} else {
					hiddenKey = "";
				}
				if(hiddenKey.equals("123")){
					XUIHelper.openSettingsActivity(MainActivity.this);
				}
			} else {
				hiddenKey = "";
			}
			int keyCode = event.getKeyCode();
			switch(keyCode){
				case KeyEvent.KEYCODE_F2:
					openSys();
					break;
				case KeyEvent.KEYCODE_0:
					Intent mIntent = new Intent();
					ComponentName comp = new ComponentName( "com.pd.apkinstaller", "com.pd.apkinstaller.MainActivity");
					mIntent.setComponent(comp);
					mIntent.setAction("android.intent.action.MAIN");
					mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					Bundle mbundle = new Bundle();  
					mbundle.putString("update_url", "http://172.19.4.240:8088/files/ottftp/7.zip");
					mbundle.putString("productInfo", "JIUZHOU");
					mIntent.putExtras(mbundle);
					startActivity(mIntent);	
					break;
				case KeyEvent.KEYCODE_1:
					XUIHelper.openInitActivity(MainActivity.this);
					break;
				case KeyEvent.KEYCODE_8:
					Hotspot();
					break;
				case KeyEvent.KEYCODE_9:
					Intent intent = new Intent(this, ShowUiVersionActivity.class);
					intent.putExtra("versionCode", AppConfig.versionCode);
					intent.putExtra("versionDate", AppConfig.versionDate);
					intent.putExtra("versionArea", AppConfig.versionArea);
					startActivity(intent);
					break;
				case KeyEvent.KEYCODE_BACK:
				case KeyEvent.KEYCODE_MENU:
				case KeyEvent.KEYCODE_HOME:
					return true;
			}
		}
		return super.dispatchKeyEvent(event);
	}
	
	private void initView(){
		showDaTextView = (TextView) findViewById(R.id.show_date);
		refreshDateFlag = true;
		new Thread(refreshDateRunnable).start();
		
		focusView = (ImageView) findViewById(R.id.focus);
		
		liveWindow = (FrameLayout) findViewById(R.id.live_window);
		liveWindow.setOnFocusChangeListener(this);
		liveWindow.setOnClickListener(this);
		initLiveWindow();
		
		liveImageView = (ImageView) findViewById(R.id.live);
		liveImageView.setOnFocusChangeListener(this);
		liveImageView.setOnClickListener(this);
		
		videoImageView = (ImageView) findViewById(R.id.video);
		videoImageView.setOnFocusChangeListener(this);
		videoImageView.setOnClickListener(this);
		
		musicImageView = (ImageView) findViewById(R.id.music);
		musicImageView.setOnFocusChangeListener(this);
		musicImageView.setOnClickListener(this);
		
		// 广告不落焦
		advImageView = (GifImageView) findViewById(R.id.adv);
//		advImageView.setOnFocusChangeListener(this);
//		advImageView.setOnClickListener(this);
		
		photoImageView = (ImageView) findViewById(R.id.photo);
		photoImageView.setOnFocusChangeListener(this);
		photoImageView.setOnClickListener(this);
		
		aboutImageView = (ImageView) findViewById(R.id.about);
		aboutImageView.setOnFocusChangeListener(this);
		aboutImageView.setOnClickListener(this);
		
		// 初始化room房间数据
		networkFlag = XUtils.isNetworkAvailable(this);
		if(networkFlag){
			initUpdateInfo.start();
			initRoomInfo();
			
		} else {
			// UI界面显示网络连接错误
//			netWorkImageView.setImageResource(R.drawable.network1);
//			marqueeTextView.setText("请检查网络");
		}
	}
	
	
	Thread initUpdateInfo = new Thread(new Runnable(){

		@Override
		public void run() {
			// TODO 自动生成的方法存根
			XLog.d("initUpdateInfo: start");
			String tempCode = AppConfig.secuCode + macNum + AppConfig.versionCode;
			String signCode = XUtils.md5(tempCode);
			XLog.d("product = "+productInfo+"tempCode: " + tempCode + ", signCode: " + signCode + ", macNum = " + macNum + "updateapiUrl = " + AppConfig.updateapiUrl + ",chips = " + chipsInfo);
			RequestParams requestParams = new RequestParams();
			requestParams.addBodyParameter("macaddr", macNum);
			requestParams.addBodyParameter("ver", AppConfig.versionCode);
			requestParams.addBodyParameter("product", productInfo);
			requestParams.addBodyParameter("chips", chipsInfo);
			requestParams.addBodyParameter("sign", signCode);
			HttpUtils httpUtils = XHttpProxy.getHttpUtils();
			
			httpUtils.send(HttpRequest.HttpMethod.POST, AppConfig.updateapiUrl, requestParams, new RequestCallBack<String>() {
			
				@Override
				public void onFailure(HttpException e, String msg) {
					
					e.printStackTrace();
					XToast.makeText(MainActivity.this, "系统繁忙，请稍后再试！").show();
				}

				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					XLog.i("initUpdateInfo.result: " + responseInfo.result);
					JSONObject jsonObject = JSON.parseObject(responseInfo.result);
					parseUpdateNum(jsonObject);
				}
			});
		}
		
	});
	
	private void parseUpdateNum(JSONObject jsonObject){
		try{
						
			String otaUpadateFlag = jsonObject.getString("upgrade");	// ota系统升级标志
			String update_url = jsonObject.getString("upgrade_url");	// ota系统升级地址
			otaUpdateOnline(otaUpadateFlag, update_url);
		} catch(Exception e){
			e.printStackTrace();
		}
	}
	
	
	private void otaUpdateOnline(String flag, String url) {
		XLog.d("otaUpdateOnline flag = "+flag+",,,url =  " + url);
		//XToast.makeText(MainActivity.this, url).show();
		if(flag.equals("true")) {
			//先删除掉旧的升级包
			if(deleteFile()) {
				Intent mIntent = new Intent();
				ComponentName comp = new ComponentName( "com.pd.apkinstaller", "com.pd.apkinstaller.MainActivity");
				mIntent.setComponent(comp);
				mIntent.setAction("android.intent.action.MAIN");
				mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				Bundle mbundle = new Bundle();  
				mbundle.putString("update_url", url);
				mbundle.putString("productInfo", productInfo);
				mIntent.putExtras(mbundle);
				startActivity(mIntent);	
			}else {
				XToast.makeText(MainActivity.this, "升级失败,请重启机顶盒").show();
			}
				
		}
	}
	
	private Boolean deleteFile() {
		Boolean Flag = true;
		File f = new File(AppConfig.OtaFilePath);
		File[] fl = f.listFiles();
	
		for (int i=0; i<fl.length; i++) {
			if(fl[i].toString().endsWith(".zip") || fl[i].toString().endsWith(".ZIP"))  
            {  
                if(fl[i].delete())  
                {  
                   Flag = true; 
                }else{  
                   Flag = false;
                }  
            } 
		}
		return Flag;
	}

	
	/**
	 * 初始化加载酒店房间详细信息
	 * 
	 * @author   long
	 * @return void
	 * @exception
	 * @author   long
	 * @since 1.0.0
	 * @date 2016年1月4日 下午4:22:17
	 */
	private void initRoomInfo(){
		if(roomInfoInitFlag == RoomInitStatus.LOADING || roomInfoInitFlag == RoomInitStatus.DONE){
			return;
		}
		roomInfoInitFlag = RoomInitStatus.LOADING;
		String macNum = MacAddressHelper.getInstance().getMacAddress(this);
		String tempCode = AppConfig.secuCode + macNum + AppConfig.versionCode;
		String signCode = XUtils.md5(tempCode);
		XLog.d("tempCode: " + tempCode + ", signCode: " + signCode);
		RequestParams requestParams = new RequestParams();
		requestParams.addBodyParameter("macaddr", macNum);
		requestParams.addBodyParameter("ver", AppConfig.versionCode);
		requestParams.addBodyParameter("sign", signCode);
		HttpUtils httpUtils = XHttpProxy.getHttpUtils();
		httpUtils.send(HttpRequest.HttpMethod.POST, AppConfig.roomUrl, requestParams, new RequestCallBack<String>() {
			
			@Override
			public void onFailure(HttpException e, String msg) {
				roomInfoInitFlag = RoomInitStatus.UNDO;
				e.printStackTrace();
//				XToast.makeText(MainActivity.this, "系统繁忙，请稍后再试！").show();
			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				XLog.i("responseInfo.result: " + responseInfo.result);
				JSONObject jsonObject = JSON.parseObject(responseInfo.result);
				parseRoomNum(jsonObject);
				roomInfoInitFlag = RoomInitStatus.DONE;
			}
		});
	}
	
	
	
	/**
	 * 解析系统参数
	 * 
	 * @author   long
	 * @param jsonObject
	 * @return void
	 * @exception
	 * @author   long
	 * @since 1.0.0
	 * @date 2016年1月4日 下午4:06:37
	 */
	private void parseRoomNum(JSONObject jsonObject){
		try{
			liveUrl = jsonObject.getString("vad_url");					// 首页左上角视频广告播放地址
			String advUrl = jsonObject.getString("ad_url");				// 广告图片链接地址
			String authFlag = jsonObject.getString("msg");				// 酒店房间认证结果码   success   error
			marqueeText = jsonObject.getString("ad_text");		        // 跑马灯文本信息
			
			
			
			
			// 设备认证成功
			if(!TextUtils.isEmpty(authFlag) && authFlag.equals("success")){
				deviceAuthFlag = true;									// 设备授权成功
				
			}
			// 直播视频
			initMediaPlayer();
			// 刷新广告图片
			if(!TextUtils.isEmpty(advUrl)){
				new AdvDownloadTask(MainActivity.this, advImageView).execute(new String[]{advUrl});
				//loadBitmap(advImageView, advUrl);
			}
			// 刷新跑马灯消息
			if(TextUtils.isEmpty(marqueeText)){
				marqueeText = "暂无提示信息";
			}
			
			if(!oldMarqueeText.equals(marqueeText)){
				marqueeTextView.setText(marqueeText);
				oldMarqueeText = marqueeText;
			}
			
		} catch(Exception e){
			e.printStackTrace();
		}
	}
	
	
	
	
	/**
	 * 进入直播视频
	 * 
	 * @author   long
	 * @return void
	 * @exception
	 * @author   long
	 * @since 1.0.0
	 * @date 2016年1月4日 下午4:16:01
	 */
	private void openPlayer() {
		//XToast.makeText(MainActivity.this, "deviceAuthFlag = true").show();
		Intent mIntent = new Intent();
		ComponentName comp = new ComponentName( "com.hotel.player", "com.hotel.player.PlayerActivity");
		mIntent.setComponent(comp);
		mIntent.setAction("android.intent.action.MAIN");
		mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Bundle mbundle = new Bundle();  
		mbundle.putString("authAddress",AppConfig.roomUrl);
		mbundle.putString("versionCode",AppConfig.versionCode);
		mIntent.putExtras(mbundle);
		startActivity(mIntent);
	}
	
	
	private void initLiveWindow(){
		mSurfaceView = (SurfaceView) this.findViewById(R.id.surfaceView);
		liveWindowLoading =  (ImageView) this.findViewById(R.id.live_loading);
		rotateAnimation = AnimationUtils.loadAnimation(this, R.anim.loading_rotate);
		liveWindowLoading.startAnimation(rotateAnimation);
        
		mSurfaceHolder = mSurfaceView.getHolder();
		mSurfaceHolder.addCallback(this);
		mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	}
	
	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		XLog.d("surfaceCreated");
		initMediaPlayer();
	}
	
	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
		XLog.d("surfaceChanged");
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		XLog.d("surfaceDestroyed");
		if (mMediaPlayer != null) {
			mMediaPlayer.release();
			mMediaPlayer = null;
		}
		super.onDestroy();
	}

	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		if(hasFocus){
			int[] location = new int[2];
			int left, top, width, height = 0;
//			if(v.getId() == R.id.marquee_text){
//				marqueeLinearLayout.getLocationInWindow(location);
//				left = (int) (location[0] - XUtils.getDimension(MainActivity.this, R.dimen.px36));
//				top = (int) (location[1] - XUtils.getDimension(MainActivity.this, R.dimen.px36));
//				width = (int) (marqueeLinearLayout.getWidth() + XUtils.getDimension(MainActivity.this, R.dimen.px72));
//				height = (int) (marqueeLinearLayout.getHeight() + XUtils.getDimension(MainActivity.this, R.dimen.px72));
//			} else {
				v.getLocationInWindow(location);
				
				left = (int) (location[0] - XUtils.getDimension(MainActivity.this, R.dimen.px36));
				top = (int) (location[1] - XUtils.getDimension(MainActivity.this, R.dimen.px36));
				width = (int) (v.getWidth() + XUtils.getDimension(MainActivity.this, R.dimen.px72));
				height = (int) (v.getHeight() + XUtils.getDimension(MainActivity.this, R.dimen.px72));
//			}
			
			XLog.i("onFocusChange: left: " + left + ", top: " + top + ", width: " + width + ", height: " + height);
			
			TvAnimator animator = new TvAnimator(focusView, v);
			animator.setTargetParams(left, top, width, height);
			animator.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		}
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()){
			case R.id.live_window:
			case R.id.live:
				openThirdApp(v.getId());
				break;
			case R.id.video:
			case R.id.music:
//			case R.id.news:
//				openThirdApp(v.getId());
//				break;
			case R.id.photo:
				//进入旅馆介绍页面
				
                //未加载到地址
				/*if(TextUtils.isEmpty(introUrl)){
					XToast.makeText(MainActivity.this, "活力星沙数据加载失败！").show();
				} else {
					XUIHelper.openPhotoActivity(MainActivity.this, introUrl);
				}
				break;*/
				
				openThirdApp(v.getId());
				
				//打开网页应用
//				if(hotelsIntroUrl == null || hotelsIntroUrl.equals("")) {
//					hotelsIntroUrl = "http://" + AppConfig.hotelsIntroIP + ":" + AppConfig.hotelsIntroPort + AppConfig.hotelsIntroPath;
//				}
//				loadUrl(hotelsIntroUrl);
//				String[] split = hotelsIntroUrl.split("/");
//				ProjectName = split[3];
//				loadUrl(hotelsIntroUrl);
				break;
				
				
			case R.id.about:
				
			
				
			// 打开系统设置界面
				openSys();
				
				break;
		}
	}
	
	
	private void loadUrl(String url) {
		Intent intent = new Intent(this, StartWebView.class);
		intent.putExtra("url", url);
		intent.putExtra("data_host", AppConfig.hotelsIntroIP);
		intent.putExtra("data_port", AppConfig.hotelsIntroPort);
		startActivity(intent);
	}
	
	/**
	 * 启动第三方APK
	 * 
	 * @author   long
	 * @param id
	 * @return void
	 * @exception
	 * @author   long
	 * @since 1.0.0
	 * @date 2015年12月28日 下午4:36:08
	 */
	private void openThirdApp(int id){
		try{
			Intent mIntent = new Intent();
			ComponentName comp = null;
			switch(id){
				case R.id.live_window:
				case R.id.live:
					openPlayer();
					return;
				case R.id.video:
					//XToast.makeText(MainActivity.this, "此业务正在建设中").show();
					if(deviceAuthFlag) {
						comp = new ComponentName("com.starcor.hunan", "com.starcor.hunan.SplashActivity");
						mIntent.setComponent(comp);
						mIntent.setAction("android.intent.action.MAIN");
						mIntent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_NEW_TASK);
						
						
						
					} else {
						XToast.makeText(MainActivity.this, "此业务未开通，请联系运营商开通").show();
					}
					break;
				case R.id.music:
					comp = new ComponentName("st.com.xiami", "com.yunos.xiami.activity.MainActivity");
					mIntent.setComponent(comp);
					mIntent.setAction("android.intent.action.MAIN");
					mIntent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_NEW_TASK);
					break;
//				case R.id.news:
//					
//					comp = new ComponentName("com.netease.newsreader.tv", "com.netease.newsreader.tv.biz.ad.AdActivity");
//					mIntent.setComponent(comp);
//					mIntent.setAction("android.intent.action.MAIN");
//					mIntent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_NEW_TASK);

					
					/*comp = new ComponentName("cn.broadin.app.fire", "cn.broadin.app.fire.FireActivity");
					mIntent.setComponent(comp);
					mIntent.setAction("android.intent.action.MAIN");
					mIntent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_NEW_TASK);*/
				
//					break;
				case R.id.photo:
					comp = new ComponentName("cn.meijx.app.album", "cn.meijx.app.album.WelcomeActivity");
					mIntent.setComponent(comp);
					mIntent.setAction("android.intent.action.MAIN");
					mIntent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_NEW_TASK);
					break;
			}
			releaseMediaPlayer();
			startActivity(mIntent);
		} catch(Exception e){
			e.printStackTrace();
			XToast.makeText(this, "应用启动失败！").show();
		}
	}
	
	/**
	 * 打开系统设置APP
	 * 
	 * @author   long
	 * @return void
	 * @exception
	 * @author   long
	 * @since 1.0.0
	 * @date 2016年1月4日 下午4:26:12
	 */
	private void openSys() {
		
		/*try {
			Intent mIntent = new Intent();
			//ComponentName comp = new ComponentName("com.mbx.settingsmbox", "com.mbx.settingsmbox.SettingsMboxActivity");  //S805方案系统设置
			ComponentName comp = new ComponentName("com.tianci.setting","com.tianci.setting.activity.MainActivity");  //九州方案系统设置			
			mIntent.setComponent(comp);
			mIntent.setAction("android.intent.action.MAIN");
			mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(mIntent);
		} catch (Exception e) {
			e.printStackTrace();
			XToast.makeText(this, "应用启动失败！").show();
		}	*/
		
		XUIHelper.openPasswordActivity(MainActivity.this);
	}
	
	private void Hotspot() {
		Intent intent = new Intent();
		intent.setClass(MainActivity.this,HotsportConfig.class);
		/*Bundle HotStatusbundle = new Bundle(); 
		HotStatusbundle.putString("HotStatus", HotStatus);
		intent.putExtras(HotStatusbundle);*/
		startActivity(intent);
	}
	
	/**
	 * 初始化视频播放串口
	 * 
	 * @author   long
	 * @return void
	 * @exception
	 * @author   long
	 * @since 1.0.0
	 * @date 2016年1月4日 下午6:21:01
	 */
	private void initMediaPlayer(){
		XLog.i("liveUrl: " + liveUrl);
		/*if(TextUtils.isEmpty(liveUrl)){
			return;
		}*/
		
		if(mMediaPlayer != null){
			mMediaPlayer.release();
			mMediaPlayer = null;
		}
		mMediaPlayer = new MediaPlayer();
		try{
			mMediaPlayer.reset();
			
			//mMediaPlayer.setDataSource(liveUrl);							// 设置视频播放地址
			
			
			mMediaPlayer.setDataSource(indexVideoFile);
			
			

//			mMediaPlayer.setDataSource(AppConfig.MAIN_VIDEO_URL);
			mMediaPlayer.setDisplay(mSurfaceHolder);
			mMediaPlayer.prepareAsync();
			
			mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			// 设置错误异常监听器
			mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
				@Override
				public boolean onError(MediaPlayer mp, int what, int extra) {
					XLog.e("play video error!!! what: " + what + ", extra: " + extra);
					XToast.makeText(getBaseContext(), "视频播放失败！").show();
					return true;
				}
			});
			mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
				@Override
				public void onCompletion(MediaPlayer mp) {
					// 视频播放完成
					XLog.d("onCompletion");
					initMediaPlayer();
//					mMediaPlayer.start();
				}
			});
			// 视频播放预处理
			mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
				@Override
				public void onPrepared(MediaPlayer mp) {
					mVideoWidth = mMediaPlayer.getVideoWidth();
					mVideoHeight = mMediaPlayer.getVideoHeight();
					XLog.d("onPrepared called, width: " + mVideoWidth + ", height: " + mVideoHeight);
					if (mVideoWidth != 0 && mVideoHeight != 0) {
						
						if(liveWindowLoading != null) {
							liveWindowLoading.clearAnimation();
							liveWindowLoading.setVisibility(View.INVISIBLE);
						}
						/* 设置视频的宽度和高度 */
						mSurfaceHolder.setFixedSize(mVideoWidth, mVideoHeight);
						/* 开始播放 */
						mMediaPlayer.start();
					}
				}
			});
			mMediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
				@Override
				public void onBufferingUpdate(MediaPlayer mp, int percent) {
					XLog.d("onBufferingUpdate, percent: " + percent);
				}
			});
			mMediaPlayer.setOnInfoListener(new MediaPlayer.OnInfoListener() {
				@Override
				public boolean onInfo(MediaPlayer mp, int what, int extra) {
					if(what == MediaPlayer.MEDIA_INFO_BUFFERING_START){
						
						liveWindowLoading.startAnimation(rotateAnimation);
						liveWindowLoading.setVisibility(View.VISIBLE);
						
					} else if(what == MediaPlayer.MEDIA_INFO_BUFFERING_END){
						
						liveWindowLoading.clearAnimation();
						liveWindowLoading.setVisibility(View.INVISIBLE);
					}
					XLog.d("setOnInfoListener, what: " + what + ", extra " + extra);
					return false;
				}
			});
		} catch(Exception e){
			e.printStackTrace();
		}
	}
	
	private Runnable refreshDateRunnable = new Runnable() {
		@Override
		public void run() {
			while(refreshDateFlag){
				Message msg = Message.obtain();
				msg.what = MSG_REFRESH_DATE;
				msg.obj = XUtils.getDateInfo();
				mHandler.sendMessage(msg);
				
				try {
					Thread.sleep(5 * 1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	};
	
	private static final int MSG_REFRESH_DATE = 1;			// 刷新主界面时间
	
	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler(){
		public void dispatchMessage(Message msg) {
			switch(msg.what){
				case MSG_REFRESH_DATE:
					showDaTextView.setText(msg.obj.toString());
					break;
			}
		};
	};
	
	/**
	 * 注册广播消息
	 * 
	 * @author   long
	 * @return void
	 * @exception
	 * @author   long
	 * @since 1.0.0
	 * @date 2016年1月4日 下午4:46:27
	 */
	private void registerBroadcastReceiver() {
		networkReceiver = new NetworkStatusReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(NET_CHANGED_ACTION);
		filter.addAction(FIRE_HAPPEN_ACTION);
		filter.addAction(FIRE_OVER_ACTION);
		registerReceiver(networkReceiver, filter);
	}
	
	public class NetworkStatusReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			XLog.e("broadcastReceiver--->action:" + action);
			if (MainActivity.NET_CHANGED_ACTION.equals(action)) {
				Bundle bundle = intent.getExtras();
				boolean flag = bundle.getBoolean("flag", false);
				XLog.d("broadcastReceiver--->network change status:" + flag);
//				refreshNetworkStatus(flag);
			} else if(MainActivity.FIRE_HAPPEN_ACTION.equals(action)){
				// 火警
				XUIHelper.openFireActivity(MainActivity.this);
				
			} else if(MainActivity.FIRE_OVER_ACTION.equals(action)){
				// 解除火警
				FireActivity.fireOver();
			}
		}
	}
	
//	private void refreshNetworkStatus(boolean flag) {
//		XLog.d("refreshNetworkStatus = " + flag);
//		if(flag){
//			networkFlag = true;
//			netWorkImageView.setImageResource(R.drawable.network);
//			// 网络恢复，刷新数据
//			
//			initRoomInfo();
//		} else {
//			networkFlag = false;
//			netWorkImageView.setImageResource(R.drawable.network1);
//			marqueeTextView.setText("请检查网络");
//			
//			// wifi掉线之后，需要重新加载数据
//			roomInfoInitFlag = RoomInitStatus.UNDO;
//		}
//	}
	
	
	private void releaseMediaPlayer() {
		if (mMediaPlayer != null) {
			// mMediaPlayer.stop();
			mMediaPlayer.release();
			mMediaPlayer = null;
		}
	}
	
	private String getPingResult() {
		String result = "failed";
		try {
			Process p = Runtime.getRuntime().exec("ping -c 3 " + AppConfig.IPaddress);
			int status = p.waitFor(); //status 只能获取是否成功，无法获取更多的信息
			if (status == 0) {  
				result="success"; 
			}    
			else 
			{ 
				result="failed"; 
			} 
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		
		return result;
		
	}
	
	/**
	 * @see android.app.Activity#onResume()
	 * @exception
	 * @author   long
	 * @since 1.0.0
	 * @date 2016年1月4日 下午5:43:02
	*/
	@Override
	protected void onResume() {
//		initMediaPlayer();
		Log.d("dyh---:","MainActivity.onResume");
		initRoomInfo();
		initMediaPlayer();
		super.onResume();
	}
	
	/**
	 * @see android.app.Activity#onPause()
	 * @exception
	 * @author   long
	 * @since 1.0.0
	 * @date 2016年3月2日 上午10:10:11
	*/
	@Override
	protected void onPause() {
		Log.d("dyh---:","MainActivity.onPause");
		roomInfoInitFlag = RoomInitStatus.UNDO;
		releaseMediaPlayer();
		super.onPause();
	}
	
	private enum RoomInitStatus{
		// 未加载   加载中   已经加载成功
		UNDO, LOADING, DONE
	}
	
	@Override
	protected void onDestroy() {
		try {
			Log.d("dyh---:","MainActivity.onDestroy");
			refreshDateFlag = false;					// 退出时间刷新线程
			
			if(networkReceiver != null){
				unregisterReceiver(networkReceiver);		// 注销广播
			}
			
			releaseMediaPlayer();
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.onDestroy();
	};
	
}
